﻿using DotNetCommon.Extensions;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace DotNetCommon;

/// <summary>
/// 类似 java 中的 Properties
/// </summary>
public static class PropertiesHelper
{
    /// <summary>
    /// 加载 Properties 文件
    /// </summary>
    /// <param name="filePath">如: c:\\test\\demo.properties</param>
    /// <param name="encoding">默认: 兼容中文乱码</param>
    /// <returns></returns>
    public static Dictionary<string, string> LoadProperties(string filePath, System.Text.Encoding encoding = null)
    {
        if (!File.Exists(filePath)) return [];
        List<string> lines = null;
        if (encoding != null)
        {
            lines = File.ReadAllLines(filePath, encoding).ToList();
        }
        else
        {
            var text = LuanMaHelper.ReadAllText(filePath);
            lines = text.SplitAndTrimTo<string>("\r", "\n");
        }
        lines = lines.Select(i => i.Trim())
            .Where(i => !i.StartsWith("//") && !i.StartsWith('#') && !i.StartsWith('='))
            .Where(i => i.Contains('='))
            .ToList();
        var dic = new Dictionary<string, string>();
        foreach (var item in lines)
        {
            var index = item.IndexOf('=');
            var key = item[..index];
            key = UnicodeHelper.DeUnicode(key);
            var value = item[(index + 1)..];
            value = UnicodeHelper.DeUnicode(value);
            dic[key] = value;
        }
        return dic;
    }
}
